USE [AdventureWorks2012]
DECLARE @schema NVARCHAR(MAX)
		, @table NVARCHAR(MAX)
		, @percent DECIMAL
		, @index NVARCHAR(MAX)
		, @qry NVARCHAR(MAX)
DECLARE @query TABLE (qry NVARCHAR(MAX))
DECLARE qIndex CURSOR FOR
	SELECT idx.name, obj.name, sch.name ,avg_fragmentation_in_percent
		FROM sys.dm_db_index_physical_stats
			(DB_ID (N'AdventureWorks'), NULL, NULL, NULL, 'DETAILED') AS idf
			JOIN sys.objects AS obj ON idf.object_id = obj.object_id
			JOIN sys.schemas AS sch ON obj.schema_id = sch.schema_id
			JOIN sys.indexes AS idx ON idx.index_id = idf.index_id
		WHERE avg_fragmentation_in_percent <> 0
OPEN qIndex
FETCH NEXT FROM qIndex INTO @index, @table, @schema, @percent
WHILE @@FETCH_STATUS = 0
BEGIN
	IF(@percent >= 30)
	BEGIN
		SET @qry = N'ALTER INDEX ' + ISNULL(QUOTENAME(@index),'') + ' ON '+ ISNULL(QUOTENAME(@schema),'') + '.' + ISNULL(QUOTENAME(@table),'') + ' REBUILD'
	END
	ELSE
	BEGIN
		IF(@percent < 30)
		BEGIN
			SET @qry = N'ALTER INDEX ' + ISNULL(QUOTENAME(@index),'') + ' ON '+ ISNULL(QUOTENAME(@schema),'') + '.' + ISNULL(QUOTENAME(@table),'') + ' REORGANIZE'
		END
	END
	INSERT INTO @query VALUES(@qry)
	FETCH NEXT FROM qIndex INTO @index, @table, @schema, @percent
END
CLOSE qIndex
DEALLOCATE qIndex
SELECT * FROM @query